package com.dave.gd.service.impl;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dave.gd.config.sysmgr.SysmgrConstants;
import com.dave.gd.service.IPermissionService;
import com.dave.gd.sysmgr.domain.entity.Permission;
import com.dave.gd.sysmgr.domain.entity.User;
import com.dave.gd.sysmgr.domain.mapper.PermissionMapper;
import com.dave.gd.sysmgr.domain.mapper.UserMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

@Service
public class PerminssionService implements IPermissionService {
    @Autowired
    private PermissionMapper permissionDao;
    @Autowired
    private UserMapper userDao;
    
    @Override
    public int insert(Permission t) {
        Date date = new Date();
        Timestamp ttmp = new Timestamp(date.getTime());
        t.setCreatetime(ttmp);
        t.setIsused(SysmgrConstants.YES_STATE);
        t.setState(SysmgrConstants.CLOSED_STATE);
        int id = this.permissionDao.insert(t);
        Permission p = new Permission();
        p.setId(id);
        p.setSort(id);
        if (t.getPid() != 0 || t.getPid() != -1) {
            p.setPname(this.permissionDao.queryByPID(t.getPid()).getPname());
        }
        return this.permissionDao.update(p);
    }
    
    @Override
    public int delete(long id) {
        return this.permissionDao.deleteById(id);
    }
    
    @Override
    public int update(Permission t) {
        
        return this.permissionDao.update(t);
    }
    
    @Override
    public Permission get(long id) {
        return this.permissionDao.queryById(id);
    }
    
    @Override
    public Page<Permission> queryPage(Integer pageNum, Integer pageSize, Permission t) {
        PageHelper.startPage(pageNum, pageSize);
        Page<Permission> pp = this.permissionDao.queryPage(t);
        
        return pp;
    }

    @Override
    public List<Permission> findPermissionListByUserId(Integer userId) {
        User u = this.userDao.queryById(userId);
        if(u==null){
            return null;
        }
        List<Permission> lp = null;
        if("admin".equals(u.getUname())){
            lp = this.permissionDao.queryAll();
        }else{
            lp = this.permissionDao.queryByUid(userId);
        }
        return lp;
    }

    @Override
    public User findUserByUname(String accountName) {
        return this.userDao.queryByUname(accountName);
    }
    
}
